package com.efounder.fragment;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.text.TextPaint;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AbsListView;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.core.xml.StubObject;
import com.efounder.activity.BaseMainHomeWithChatActivity;
import com.efounder.activity.TabBottomActivity;
import com.efounder.adapter.MyViewPagerAdapter;
import com.efounder.chat.db.WeChatDBManager;
import com.efounder.chat.event.SystemInitOverEvent;
import com.efounder.chat.model.NewMessageEvent;
import com.efounder.chat.model.UpdateBadgeViewEvent;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.frame.baseui.BaseFragment;
import com.efounder.frame.utils.Constants;
import com.efounder.imageloader.GlideImageLoader;
import com.efounder.message.manager.JFMessageManager;
import com.efounder.message.struct.IMStruct002;
import com.efounder.mobilecomps.contacts.User;
import com.efounder.ospmobilelib.R;
import com.efounder.service.Registry;
import com.efounder.util.MenuGnqxUtil;
import com.efounder.widget.AbSlidingPlayView;
import com.efounder.widget.CommonGridView;
import com.efounder.widget.CustomViewPager;
import com.pansoft.resmanager.ResFileManager;
import com.utilcode.util.ActivityUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;


/**
 * 支持条目的增删，不支持修改
 * TODO这个fragment的数据来源应该来自数据库比较好
 */
@SuppressLint("NewApi")
public class MainFragment extends BaseFragment {

    private static final String TAG = "MainFragment";

    private View rootView;//缓存Fragment view
    //顶部
    private RelativeLayout topContentLl;
    private AbSlidingPlayView mSlidingPlayView;
    //中部view
    private CustomViewPager viewPager;
    //标题
    private String titleStr;
    // 中部gridview数据源
    private Hashtable hashtable; //资源文件中表头的map
    private StubObject mainMenuItem; //从资源文件文件读取的应用stubobject
    private List<StubObject> xmlMenus; // 应用模块中子模块stubList
    private ArrayList<StubObject> middleGridList; //根据功能权限过滤后的list、用户自定义之后的list
    private ArrayList<StubObject> perGridStub; //分页之后的stubList
    private List<View> viewPagerList;//viewpager的数据源

    //中部gridview的变量、常量
    private int totalPage;
    private final int mPageSize = 12;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        if (null != savedInstanceState) {
            xmlMenus = (List<StubObject>) savedInstanceState
                    .getSerializable("databack");
            titleStr = (String) savedInstanceState.getSerializable("title");
        }

        //初始化参数
        if (getArguments() != null) {
            mainMenuItem = (StubObject) getArguments().getSerializable("stubObject");
            if (mainMenuItem != null) {
                xmlMenus = Registry.getRegEntryList((String) mainMenuItem.getID());
                hashtable = mainMenuItem.getStubTable();
                titleStr = mainMenuItem.getCaption();
            }
        }
        //初始化view
        if (rootView == null) {
            rootView = inflater.inflate(R.layout.my_fragment_ui_withtilte, container, false);

        /* 1 滚动图片 */
            topContentLl = (RelativeLayout) rootView.findViewById(R.id.topContent);
            // 组和个AbSlidingPlayView
            mSlidingPlayView = new AbSlidingPlayView(getActivity());
            mSlidingPlayView.setNavHorizontalGravity(Gravity.CENTER);

            parseShufflingFigure();//轮播图放置图片
            mSlidingPlayView.startPlay();
            // 设置高度
            Display d = this.getActivity().getWindowManager().getDefaultDisplay();
            // 更改次参数可以改变首页上方显示图片的大小
            mSlidingPlayView.setLayoutParams(new AbsListView.LayoutParams(LayoutParams.MATCH_PARENT, (int) (d.getWidth() / 1.8)));
                    // LayoutParams.FILL_PARENT, (int) (d.getWidth() / 3.14)));

            mSlidingPlayView.setPadding(0, 0, 0, 10);
            topContentLl.addView(mSlidingPlayView);

            //共享项目要求提供tip
            if (hashtable.containsKey("isShowTip")) {
                String isShowTip = (String) hashtable.get("isShowTip");
                if (isShowTip.equals("true")) {
                    TextView lable = new TextView(getContext());
                    User user = WeChatDBManager.getInstance().
                            getOneUserById(Integer.valueOf(EnvironmentVariable.getProperty(Constants.CHAT_USER_ID)));
                    String userName = user.getNickName();

                    lable.setText("Hi," + userName);
                    lable.setTextSize(30);
                    lable.setTextColor(getResources().getColor(R.color.white));
                    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
                    params.addRule(RelativeLayout.CENTER_IN_PARENT);
                    TextPaint tp = lable.getPaint();
                    tp.setFakeBoldText(true);
                    topContentLl.addView(lable, params);
                }
            }

            // 解决冲突问题
            mSlidingPlayView
                    .setOnItemClickListener(new AbSlidingPlayView.AbOnItemClickListener() {
                        @Override
                        public void onClick(int position) {
                        }
                    });

            mSlidingPlayView
                    .setOnPageChangeListener(new AbSlidingPlayView.AbOnChangeListener() {
                        @Override
                        public void onChange(int position) {
                        }
                    });


            /*中部gridview*/
            if (null != xmlMenus && xmlMenus.size() > 0) {
                MenuGnqxUtil.handleGNQX(xmlMenus);//处理功能权限
            }

            viewPager = (CustomViewPager) rootView.findViewById(R.id.viewpager);
            viewPager.setScrollable(true);
            middleGridList = filterGrid();


            RelativeLayout bottomGridContain = (RelativeLayout) rootView
                    .findViewById(R.id.rightbottomgrid);
            bottomGridContain.setVerticalScrollBarEnabled(false);


            //标题栏
            RelativeLayout include = (RelativeLayout) rootView
                    .findViewById(R.id.include);
            // 判断fragment是否是单独的
//            if (isAlone()) {
//                include.setVisibility(View.VISIBLE);
//            } else {
//                include.setVisibility(View.GONE);
//            }
            include.setVisibility(View.GONE);

            initData();

            initBadge();
            //注册监听
            if (!EventBus.getDefault().isRegistered(this))
                EventBus.getDefault().register(this);

        } else {
            //缓存的rootView需要判断是否已经被加过parent， 如果有parent需要从parent删除，要不然会发生这个rootview已经有parent的错误。
            ViewGroup parent = (ViewGroup) rootView.getParent();
            if (parent != null) {
                parent.removeView(rootView);
            }
        }
        return rootView;
    }
    @Subscribe(threadMode = ThreadMode.MAIN, priority = 1)
    public void onSolveMessageEvent(SystemInitOverEvent event) {
        initBadge();
    }

    private void initData() {
        //总的页数向上取整
        totalPage = (int) Math.ceil(middleGridList.size() * 1.0 / mPageSize);
        viewPagerList = new ArrayList<>();
        for (int i = 0; i < totalPage; i++) {
            //每个页面都是inflate出一个新实例
            CommonGridView gridView = (CommonGridView) View.inflate(this.getContext(), R.layout.item_gridview, null);
            gridView.setFocusable(false);//解决scorallview 不再最顶部的问题
            gridView.setSettingInterface(new CommonGridView.SettingInterface() {
                @Override
                public void click() {
                    MenuFragment menuFragment = new MenuFragment();
                    TabBottomActivity tabActivity = TabBottomActivity
                            .getInstance();
                    menuFragment.setFromString(titleStr);
                    menuFragment.setBadgeType(MainFragment.this.getBadgeType());
                    menuFragment.setXmlBH((String) mainMenuItem.getID());
                    if (tabActivity == null) {
                        ((BaseMainHomeWithChatActivity)ActivityUtils.getTopActivity()).jumpAndStoreStack(menuFragment);
                    } else {
                        tabActivity.jumpAndStoreStack(menuFragment);
                    }
                }
            });
            int subEndPosition = 0;
            if (mPageSize * (i + 1) - 1 < middleGridList.size()) {
                subEndPosition = mPageSize * (i + 1);
            } else {
                subEndPosition = middleGridList.size();
            }

            perGridStub = new ArrayList(middleGridList.subList(i * mPageSize, subEndPosition));
            gridView.setArrayList(perGridStub);
            //每一个GridView作为一个View对象添加到ViewPager集合中
            viewPagerList.add(gridView);
        }
        //设置ViewPager适配器
        viewPager.setAdapter(new MyViewPagerAdapter(viewPagerList));
    }

    private void initBadge() {
        if (null== perGridStub)
            return;
        String badgeTypeArrayString = EnvironmentVariable.getProperty("Badge" + MainFragment.this.getBadgeType(), "");
        String[] badgeTypeArray = badgeTypeArrayString.split(",");
        for (int i = 0; i < perGridStub.size(); i++) {
            StubObject stubObject = perGridStub.get(i);
            String type = stubObject.getString("viewType", "");
            //if(type.equals("appacount")){
            String appId = stubObject.getString("appId", "");
            String isShowBadge = stubObject.getString("isShowBadge", "true");
            if (appId.equals("")) continue;
            if (badgeTypeArray.length > 0) {
                for (int j = 0; j < badgeTypeArray.length; j++) {
                    if (badgeTypeArray[j].equals(appId)) break;
                    if (j == badgeTypeArray.length - 1) {
                        EnvironmentVariable.setProperty("Badge" + MainFragment.this.getBadgeType(), badgeTypeArrayString + "," + appId);
                    }
                }
            }
            int unReadCount = JFMessageManager.getInstance().getUnReadCount(Integer.parseInt(appId), (byte) 0);
            if (unReadCount == 0) {
                stubObject.setInt("badgeNum", -1);
            } else {
                stubObject.setInt("badgeNum", unReadCount);
            }


            if (!isShowBadge.equals("true")) {
                if (unReadCount > 0) {
                    stubObject.setInt("badgeNum", 0);
                }
            }
        }

        for (int i = 0; i < viewPagerList.size(); i++) {
            CommonGridView commonGridView = (CommonGridView) viewPagerList.get(i);
            commonGridView.update();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public synchronized void onSolveMessageEvent(NewMessageEvent event) {

        IMStruct002 imStruct002 = event.getImStruct002();
        int fromUserId = imStruct002.getFromUserId();
        for (int i = 0; i < middleGridList.size(); i++) {
            StubObject stubObject = middleGridList.get(i);
            String type = stubObject.getString("viewType", "");

            String appId = stubObject.getString("appId", "");
            String isShowBadge = stubObject.getString("isShowBadge", "true");


            if (appId.equals("")) continue;
            int unReadCount = JFMessageManager.getInstance().getUnReadCount(Integer.parseInt(appId), (byte) 0);
            if (fromUserId == Integer.parseInt(appId)) {
                if (unReadCount == 0) {
                    stubObject.setInt("badgeNum", -1);
                } else {
                    stubObject.setInt("badgeNum", unReadCount);
                }
                if (!isShowBadge.equals("true")) {
                    if (unReadCount > 0) {
                        stubObject.setInt("badgeNum", 0);
                    }
                }
                //刷新某一页的gridview
                int page = i / mPageSize;
                CommonGridView commonGridView = (CommonGridView) viewPagerList.get(page);
                commonGridView.update();


            }
        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onSolveMessageEvent(UpdateBadgeViewEvent event) {
        int fromUserId = Integer.parseInt(event.getUserID());
        byte chatType = event.getChatType();
        //如果是群聊，直接返回
        if (chatType == (byte) 1)
            return;
        for (int i = 0; i < middleGridList.size(); i++) {
            StubObject stubObject = middleGridList.get(i);
            String appId = stubObject.getString("appId", "");
            String isShowBadge = stubObject.getString("isShowBadge", "true");

            if (appId.equals("")) continue;
            int unReadCount = JFMessageManager.getInstance().getUnReadCount(Integer.parseInt(appId), (byte) 0);
            if (fromUserId == Integer.parseInt(appId)) {
                if (unReadCount == 0) {
                    stubObject.setInt("badgeNum", -1);
                } else {
                    stubObject.setInt("badgeNum", unReadCount);
                }
            }
            if (!isShowBadge.equals("true")) {
                if (fromUserId == Integer.parseInt(appId)) {
                    if (unReadCount > 0) {
                        stubObject.setInt("badgeNum", 0);
                    }
                }
            }
            //刷新某一页的gridview
            int page = i / mPageSize;
            CommonGridView commonGridView = (CommonGridView) viewPagerList.get(page);
            commonGridView.update();
        }
    }

    /**
     * 解析轮播图 图片
     */
    private void parseShufflingFigure() {
        if (hashtable.containsKey("carouseImage")) {
            String[] images = ((String) hashtable.get("carouseImage")).split("\\|");
            if (images == null || images.length == 0) {
                loadResImage();
            } else {
                for (int i = 0; i < images.length; i++) {
                    String imagePath = "file://" + ResFileManager.IMAGE_DIR + "/" + images[i];
                    try {
                        ImageView iv = new ImageView(this.getActivity());
                        iv.setScaleType(ScaleType.FIT_XY);
                       //Picasso.with(getContext()).load(imagePath).into(iv);
                        GlideImageLoader.getInstance().displayImage(getContext(),iv, imagePath, R.drawable.default_img);


                        mSlidingPlayView.addView(iv);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

        } else {
            loadResImage();
        }
    }

    //加载程序中自带的轮播图
    private void loadResImage() {
        ImageView iv2 = new ImageView(this.getActivity());
        iv2.setImageResource(R.drawable.bg_about);
        iv2.setScaleType(ScaleType.FIT_XY);

        ImageView iv3 = new ImageView(this.getActivity());
        iv3.setImageResource(R.drawable.bg_about);
        iv3.setScaleType(ScaleType.FIT_XY);
        ImageView iv4 = new ImageView(this.getActivity());
        iv4.setImageResource(R.drawable.bg_about);
        iv4.setScaleType(ScaleType.FIT_XY);
        //mSlidingPlayView.addView(iv1);
        mSlidingPlayView.addView(iv2);
        mSlidingPlayView.addView(iv3);
        mSlidingPlayView.addView(iv4);
    }

    @Override
    public void onResume() {
        // TODO Auto-generated method stub

        super.onResume();
    }

    @Override
    public void onPause() {
        // TODO Auto-generated method stub
        super.onPause();

    }

    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        EventBus.getDefault().unregister(this);

    }

    /**
     * 将xml的数据，与用户配置的数据（已保存在本地）对比
     * @return
     */
    private ArrayList<StubObject> filterGrid() {
        middleGridList = new ArrayList<StubObject>();
        if (null == xmlMenus || xmlMenus.size() == 0) {
            return middleGridList;
        }
        String userName = EnvironmentVariable.getUserName();
        String localString = EnvironmentVariable.getProperty(userName + "/" + titleStr, "");
        Map<String, String> localMap = new HashMap();
        if (!localString.equals("")) {
            java.util.StringTokenizer items;
            for (StringTokenizer entrys = new StringTokenizer(localString, "^"); entrys.hasMoreTokens();
                 localMap.put(items.nextToken(), items.hasMoreTokens() ? ((String) (items.nextToken())) : null))
                items = new StringTokenizer(entrys.nextToken(), "'");
        }

        boolean isNeedSaveAgain = false;
        for (int i = 0; i < xmlMenus.size(); i++) {
            StubObject xmlStuObject = xmlMenus.get(i);
            String xmlid = xmlStuObject.getString("id", "");
            if (!localMap.isEmpty()) {
                if (localMap.containsKey(xmlid)) {
                    String value = localMap.get(xmlid);
                    if (value.equals("1")) {
                        middleGridList.add(xmlStuObject);
                    }
                } else {
                    isNeedSaveAgain = true;
                    middleGridList.add(xmlStuObject);
                    localMap.put(xmlid, "1");
                }

            } else {
                StubObject extEdObject = (StubObject) xmlMenus.get(i);
                middleGridList.add(extEdObject);
                localMap.put(xmlid, "1");
                isNeedSaveAgain = true;
            }
        }

        if (isNeedSaveAgain) {
            Map.Entry entry;
            StringBuffer sb = new StringBuffer();
            for (Iterator iterator = localMap.entrySet().iterator(); iterator.hasNext(); ) {
                entry = (java.util.Map.Entry) iterator.next();
                sb.append(entry.getKey().toString()).append("'").append(null == entry.getValue() ? "" :
                        entry.getValue().toString()).append(iterator.hasNext() ? "^" : "");
            }

            EnvironmentVariable.setProperty(userName + "/" + titleStr, sb.toString());
        }

        return middleGridList;
    }

//    public void setListViewHeightBasedOnChildren(ListView listView) {
//        // 获取ListView对应的Adapter
//        ListAdapter listAdapter = listView.getAdapter();
//        if (listAdapter == null) {
//            return;
//        }
//        int totalHeight = 0;
//        for (int i = 0; i < listAdapter.getCount(); i++) { // listAdapter.getCount()返回数据项的数目
//            View listItem = listAdapter.getView(i, null, listView);
//            listItem.measure(0, 0); // 计算子项View 的宽高
//            totalHeight += listItem.getMeasuredHeight(); // 统计所有子项的总高度
//        }
//        ViewGroup.LayoutParams params = listView.getLayoutParams();
//        params.height = totalHeight
//                + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
//        // listView.getDividerHeight()获取子项间分隔符占用的高度
//        // params.height最后得到整个ListView完整显示需要的高度
//        listView.setLayoutParams(params);
//    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        // TODO Auto-generated method stub
        super.onSaveInstanceState(outState);
        outState.putSerializable("databack", (Serializable) xmlMenus);
        outState.putSerializable("title", titleStr);
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refreshGrid() {
        //cgv.refresh();
        middleGridList = filterGrid();
        initData();
    }

}
